package com.cn.shuangzi.util.download;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.util.SZFileUtil;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.download.listener.ProgressHelper;
import com.cn.shuangzi.util.download.listener.UIProgressListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by CN.
 */

public class SZDownloaderUtil {

    public static void download(String downloadUrl, final String fileName, final HttpDownloadListener httpDownloadListener) {

        //这个是ui线程回调，可直接操作UI
        final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
            @Override
            public void onUIProgress(long bytesRead, long contentLength, boolean done) {
                if(httpDownloadListener!=null) {
                    httpDownloadListener.onProgress(bytesRead, contentLength, done);
                }
//                Util.log("bytesRead:" + bytesRead);
//                Util.log("contentLength:" + contentLength);
//                Util.log("done:" + done);
//                if (contentLength != -1) {
                    //长度未知的情况下回返回-1
//                    Util.log((100 * bytesRead) / contentLength + "% done");
//                }
//                Util.log("================================");
                //ui层回调
//                downloadProgeress.setProgress((int) ((100 * bytesRead) / contentLength));
            }

            @Override
            public void onUIStart(long bytesRead, long contentLength, boolean done) {
                super.onUIStart(bytesRead, contentLength, done);
                if(httpDownloadListener!=null) {
                    httpDownloadListener.onStart(bytesRead, contentLength, done);
                }
            }

            @Override
            public void onUIFinish(long bytesRead, long contentLength, boolean done) {
                super.onUIFinish(bytesRead, contentLength, done);
                if(httpDownloadListener!=null) {
                    httpDownloadListener.onFinish(bytesRead, contentLength, done);
                }
            }
        };

        //构造请求
        final Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        //包装Response使其支持进度回调

        ProgressHelper.addProgressResponseListener(SZRetrofitManager.getInstance().getOkInstance(downloadUrl,null,null), uiProgressResponseListener).newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                SZUtil.log("error :" + e);
                if(httpDownloadListener!=null) {
                    httpDownloadListener.onError();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream;
                try {
                    File file = new File(SZFileUtil.getInstance().getDownloadPathName(),fileName);
                    fileOutputStream = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                }catch(Exception e){
                    e.printStackTrace();
                    if(httpDownloadListener!=null) {
                        httpDownloadListener.onError();
                    }
                }
            }
        });
    }
    public interface  HttpDownloadListener{
        void onProgress(long bytesRead, long contentLength, boolean done);
        void onStart(long bytesRead, long contentLength, boolean done);
        void onFinish(long bytesRead, long contentLength, boolean done);
        void onError();
    }
}
